/***********************************************
 @Name :        小谭老师
 @Time :        2025-2-22
 @Email :       tan.zhipeng@outlook.com
 @Comment :     功能窗口 天气预报
 @FileName :    widget_funcd_weather.cpp
 @Version :     1.0
************************************************/


#include "widget_funcd_weather.h"
#include "ui_widget_funcd_weather.h"
#include <QDebug>
#include <QScrollBar>

Widget_funcD_Weather::Widget_funcD_Weather(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget_funcD_Weather)
{
    ui->setupUi(this);
    // 连接数据库
    cityDao=new CityDao("127.0.0.1","qt_pro","root","8");
    // 打开数据库连接
    if (!cityDao->openDatabase()) {
        qDebug() << "Failed to open database!";
    }else{
        qDebug()<< "数据库连接成功";
    }
    
    // 添加水平布局
    QHBoxLayout *top_layout=new QHBoxLayout(ui->widget);
    // 创建输入框
    searchInput = new QLineEdit(ui->widget);
    searchInput->setPlaceholderText("请输入地区"); // 设置提示文字
    // 设置样式表
    searchInput->setStyleSheet(R"(
        QLineEdit{
            background-color:#ffffff;
            border:1px solid #ffffff;
            border-radius: 8px;
            padding: 5px 10px;
            padding-right: 30px;
        }
    )");
    
    // 创建结果显示列表 - 初始隐藏
    // 创建浮动结果窗口
    // resultPopup = new QWidget(this, Qt::Popup | Qt::FramelessWindowHint);
    resultPopup = new QWidget(this, Qt::Tool | Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus);
    resultPopup->setStyleSheet("background-color: white; border: 1px solid #CCCCCC;border-radius: 2px;");
    resultPopup->setVisible(false);
    
    // 创建结果列表
    resultView = new QListView(resultPopup);
    model = new QStandardItemModel(this);
    resultView->setModel(model);
    resultView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    resultView->setFocusPolicy(Qt::NoFocus);
    resultView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    resultView->verticalScrollBar()->setStyleSheet(R"(
QScrollBar:vertical {
        border: none;
        background: #F0F0F0;
        width: 12px;
        margin: 0px;
    }
    
    QScrollBar::handle:vertical {
        background: #C0C0C0;
        border-radius: 6px;
        min-height: 20px;
    }
QScrollBar::handle:vertical:hover {
        background: #A0A0A0;
    }
QScrollBar::add-page:vertical, 
    QScrollBar::sub-page:vertical {
        background: #F0F0F0;
    }
QScrollBar::add-line:vertical, 
    QScrollBar::sub-line:vertical {
        border: none;
        background: none;
        width: 0;
        height: 0;
    }
    
)");
    // 设置列表布局
    QVBoxLayout *popupLayout = new QVBoxLayout(resultPopup);
    popupLayout->setContentsMargins(0, 0, 0, 0);
    popupLayout->addWidget(resultView);
    
    // 设置列表最大高度（显示5项）
    // resultView->setFixedWidth(searchInput->width());s
    resultView->setMinimumHeight(0);
    

    // // 创建搜索按钮
    // searchButton = new QPushButton(); // 使用搜索图标
    // searchButton->setIcon(QIcon(":/搜索"));
    
    // 创建城市文本的label标签
    city_label=new QLabel(ui->widget);
    city_label->setStyleSheet(R"(
        QLabel {
            font-size: 28px;
            font-weight: bold;
        }
    )");
    city_label->setText("长沙市");
    city_label->setFixedSize(280,60);
    
    
    // 将输入框和按钮添加到布局
    top_layout->addWidget(searchInput);
    // top_layout->addWidget(searchButton);
    top_layout->addWidget(city_label);
    
    QHBoxLayout *widget_2_layout=new QHBoxLayout(ui->widget_2);
    curr_weather_box1=new CurrWeatherBox(ui->widget_2);
    curr_weather_box2=new CurrWeatherBox(ui->widget_2,true);
    curr_weather_box3=new CurrWeatherBox(ui->widget_2);
    widget_2_layout->addWidget(curr_weather_box1);
    widget_2_layout->addWidget(curr_weather_box2);
    widget_2_layout->addWidget(curr_weather_box3);
    
    
    //widget_3气温折线图
    // 初始化折线图并添加到布局
    m_tempChart = new TemperatureChart(this);
    // 假设主窗口有一个布局叫mainLayout，添加折线图
    QVBoxLayout *widget_3_layout=new QVBoxLayout(ui->widget_3);
    widget_3_layout->setAlignment(Qt::AlignHCenter);
    m_tempChart->setFixedSizeMode(true,680,300);
    widget_3_layout->addWidget(m_tempChart);
    
    // 下方widget_4的水平布局
    QHBoxLayout *widget_4_layout=new QHBoxLayout(ui->widget_4);
    weatherBox_1=new WeatherDisplayBox(ui->widget_4);
    weatherBox_1->set_color(QColor(qRgba(255,255,255,255)));
    weatherBox_2=new WeatherDisplayBox(ui->widget_4);
    weatherBox_2->set_color(QColor(qRgba(255,255,255,255)));
    weatherBox_3=new WeatherDisplayBox(ui->widget_4);
    weatherBox_3->set_color(QColor(qRgba(255,255,255,255)));
    weatherBox_4=new WeatherDisplayBox(ui->widget_4);
    weatherBox_4->set_color(QColor(qRgba(255,255,255,255)));
    weatherBox_5=new WeatherDisplayBox(ui->widget_4);
    weatherBox_5->set_color(QColor(qRgba(255,255,255,255)));
    weatherBox_6=new WeatherDisplayBox(ui->widget_4);
    weatherBox_6->set_color(QColor(qRgba(255,255,255,255)));
    weatherBox_7=new WeatherDisplayBox(ui->widget_4);
    weatherBox_7->set_color(QColor(qRgba(255,255,255,255)));
    widget_4_layout->addWidget(weatherBox_1);
    widget_4_layout->addWidget(weatherBox_2);
    widget_4_layout->addWidget(weatherBox_3);
    widget_4_layout->addWidget(weatherBox_4);
    widget_4_layout->addWidget(weatherBox_5);
    widget_4_layout->addWidget(weatherBox_6);
    widget_4_layout->addWidget(weatherBox_7);
    box_arr.append(weatherBox_1);
    box_arr.append(weatherBox_2);
    box_arr.append(weatherBox_3);
    box_arr.append(weatherBox_4);
    box_arr.append(weatherBox_5);
    box_arr.append(weatherBox_6);
    box_arr.append(weatherBox_7);
    

    
    // http get请求天气数据
    manager = new QNetworkAccessManager(this);
    connect(manager, &QNetworkAccessManager::finished, this, &Widget_funcD_Weather::onWeatherReplyFinished);
    QString url = QString("http://t.weather.itboy.net/api/weather/city/101250101");
    QNetworkRequest request(url);
    manager->get(request);
    
    // 搜索按钮点击
    // connect(searchButton,&QPushButton::clicked,this,&Widget_funcD_Weather::searchButtonClick);
    // 输入框内容改变信号
    connect(searchInput,&QLineEdit::textChanged,this,&Widget_funcD_Weather::searchInputTextChange);
    
    // 结果列表项点击信号
    connect(resultView, &QListView::clicked, this, &Widget_funcD_Weather::onResultViewClicked);
    
}

Widget_funcD_Weather::~Widget_funcD_Weather()
{
    delete ui;
    // 关闭数据库连接
    cityDao->closeDatabase();
}

// 列表项点击处理
void Widget_funcD_Weather::onResultViewClicked(const QModelIndex &index)
{
    QString selectedText = index.data().toString();
    searchInput->setText(selectedText);
    qDebug()<<selectedText;
    // 隐藏列表
    resultPopup->hide();
    
    // 发送http请求数据
    City *city=cityDao->getCityIDByName(selectedText);
    QString url = QString("http://t.weather.itboy.net/api/weather/city/%1").arg(city->cityId);
    QNetworkRequest request(url);
    manager->get(request);
    delete city;
}

// 搜索按钮点击
// void Widget_funcD_Weather::searchButtonClick()
// {
// }

// 输入框内容改变信号
void Widget_funcD_Weather::searchInputTextChange(const QString &text)
{
    model->clear(); // 清空模型
    
    if (text.isEmpty()) {
        // 隐藏列表
        resultPopup->hide();
        return; // 如果输入为空，直接返回
    }
    
    // 数据库查询 得到所有id
    searchInputDataList=cityDao->searchCitiesByName(text);
    if(searchInputDataList->size()>0){
        // 遍历数据源
        for (const City item : *searchInputDataList) {
            QStandardItem *modelItem = new QStandardItem(item.cityName);
            model->appendRow(modelItem);
        }
        // 调整弹出窗口大小
        int rowHeight = resultView->sizeHintForRow(0);
        int visibleRows = qMin(5, searchInputDataList->size());
        int popupHeight = rowHeight * visibleRows + 5; // 加一点边距
        
        resultPopup->setFixedHeight(popupHeight);
        resultView->setFixedHeight(popupHeight);
        
        // 定位弹出窗口（输入框下方）
        positionResultPopup();
        resultPopup->show();
        resultPopup->raise();
        
    }
    
}

// 请求天气数据的响应
void Widget_funcD_Weather::onWeatherReplyFinished(QNetworkReply *reply)
{
    if (reply->error() != QNetworkReply::NoError) {
        qDebug()<< "请求失败!";
        reply->deleteLater();
        return;
    }
    
    QByteArray data = reply->readAll();
    reply->deleteLater();
    
    QJsonParseError parseError;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &parseError);
    
    if (parseError.error != QJsonParseError::NoError) {
        qDebug()<< "json解析错误";
        return;
    }
    WeatherData weather=WeatherData::fromJson(jsonDoc.object());
    // 城市信息
    city_label->setText(weather.cityInfo.parent+"  •  "+weather.cityInfo.city);
    // 当天天气数据
    QString notic=QString("空气质量 %1").arg(weather.forecast[0].aqi);
    notic+=QString("\n风向 ")+weather.forecast[0].fx;
    notic+=QString("\n风力 ")+weather.forecast[0].fl;
    notic+=QString("\n温馨提示 ")+weather.forecast[0].notice;
    // 折线图数组
    QList<TempData> dataList;
    // 填充 七天 天气数据
    for(int i=0;i<box_arr.size();i++){
        if(i==0){
            // 当天天气数据
            curr_weather_box1->set_text(QPixmap(QString(":/")+weather.forecast[i].type));
            curr_weather_box2->set_text(weather.date.toString("yyyy MM dd"),weather.forecast[0].high
                                        ,weather.forecast[0].low,weather.forecast[0].type);
            curr_weather_box3->set_text(notic);
        }
        box_arr[i]->set_weekday_label(weather.forecast[i].week);
        box_arr[i]->set_weatherPixmap_label(QPixmap(QString(":/")+weather.forecast[i].type));
        QString high=extractNumber(weather.forecast[i].high);
        QString low=extractNumber(weather.forecast[i].low);
        box_arr[i]->set_wendu_label(low,high);
        
        // 折线图数据
        // 解析JSON后得到7天数据，转换为QList<TempData>
        TempData data;
        data.date = weather.forecast[i].date;  // 示例日期
        data.high = high.toInt();  // 示例最高温
        data.low =low.toInt();   // 示例最低温
        dataList.append(data);
        
    }
    // 设置数据到折线图
    m_tempChart->setData(dataList);

}
// 定位结果弹出窗口
void Widget_funcD_Weather::positionResultPopup()
{
    if (!searchInput || !resultPopup) return;
    
    // 计算全局位置
    QPoint globalPos = searchInput->mapToGlobal(QPoint(0, searchInput->height()));
    
    // 调整位置确保在屏幕内
    QRect screen = QApplication::desktop()->availableGeometry(this);
    if (globalPos.y() + resultPopup->height() > screen.bottom()) {
        // 如果下方空间不足，显示在输入框上方
        globalPos = searchInput->mapToGlobal(QPoint(0, -resultPopup->height()));
    }
    
    resultPopup->move(globalPos);
    resultPopup->setFixedWidth(searchInput->width());
}

// 窗口大小变化时需要重新定位
void Widget_funcD_Weather::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    if (resultPopup && resultPopup->isVisible()) {
        positionResultPopup();
    }
}

// 字符串中提取数值
QString Widget_funcD_Weather::extractNumber(const QString& input) {
    QRegularExpression re("\\d+");  // 匹配一个或多个数字
    QRegularExpressionMatch match = re.match(input);
    if (match.hasMatch()) {
        return match.captured(0);  // 返回第一个匹配到的数字
    }
    return "";  // 若没找到匹配的数字，就返回空字符串
}
